package com.automailerbot.sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class SmsActivateService {

    private final String apiKey;

    public SmsActivateService(String apiKey) {
        this.apiKey = apiKey;
    }

    public String requestPhoneNumber(String service, String country) throws Exception {
        String url = String.format(
                "https://sms-activate.org/stubs/handler_api.php?api_key=%s&action=getNumber&service=%s&country=%s",
                apiKey, service, country
        );

        String response = sendGet(url);
        if (!response.startsWith("ACCESS_NUMBER")) {
            throw new Exception("获取号码失败: " + response);
        }

        return response.split(":")[1]; // 返回 ID
    }

    public String getVerificationCode(String id) throws Exception {
        String url = String.format(
                "https://sms-activate.org/stubs/handler_api.php?api_key=%s&action=getStatus&id=%s",
                apiKey, id
        );

        for (int i = 0; i < 15; i++) {
            TimeUnit.SECONDS.sleep(4);
            String result = sendGet(url);
            if (result.startsWith("STATUS_OK:")) {
                return result.split(":")[1];
            } else if (!result.equals("STATUS_WAIT_CODE")) {
                throw new Exception("验证码获取失败: " + result);
            }
        }

        throw new Exception("等待验证码超时");
    }

    public void cancelNumber(String id) throws Exception {
        String url = String.format(
                "https://sms-activate.org/stubs/handler_api.php?api_key=%s&action=setStatus&status=8&id=%s",
                apiKey, id
        );
        sendGet(url);
    }

    private String sendGet(String urlStr) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            return in.readLine();
        }
    }
}
